(function(window) {

    var MyUpload = function(rootid, maxnum,countChangeCallback) {


        if (typeof maxnum == "undefined" || isNaN(maxnum) || maxnum < 0)
            this.maxnum = 5;
        else {
            this.maxnum = maxnum;
        }

        this.rootid = rootid;
        this.rootNode;
        this.num = 0;
        this.currentCount = 0;
		this.size=70;
		this.countChangeCallback = countChangeCallback;


        if (typeof MyUpload._inited_ == "undefined") {

            MyUpload.prototype.init = function() {
                this.rootNode = this.initParentNode(this.rootid);
                this.createChild(this);
            }


            MyUpload.prototype.css = function(obj, style) {
                for (var k in style) {
                    obj.style[k] = style[k];
                }
            }

            MyUpload.prototype.myCreateElement = function(tag, style, attr) {
                var _this = this; //test
                var obj = document.createElement(tag);
                if (typeof style != "undefined")
                    for (var k in style) {
                        obj.style[k] = style[k];
                    }
                if (typeof attr != "undefined")
                    for (var k in attr) {
                        var attrNode = document.createAttribute(k);
                        attrNode.nodeValue = attr[k];
                        obj.setAttributeNode(attrNode);
                    }
                return obj;
            }



            MyUpload.prototype.initParentNode = function(id) {
                var parent = document.getElementById(id);
                this.css(parent, { overflow: "hidden" });
                return parent;
            }

            MyUpload.prototype.createChild = function(upobj) {
                var _this = this; //test
                if (upobj.currentCount >= upobj.maxnum) return;

                var rootDiv = upobj.myCreateElement("div", { "width": (this.size+30)+"px", "height": (this.size+30)+"px", "padding": "5px", "margin": "5px", "float": "left" });
                //
                var outerDiv = upobj.myCreateElement("div", { "width": (this.size+20)+"px", "height": (this.size+20)+"px", "position": "relative" });
                //
                var innerDiv1 = upobj.myCreateElement("div", { "width": "30px", "height": "30px", "position": "absolute", "top": "0px", "z-index": "999", "right": "0px", "display": "none" });

                var closeImg = upobj.myCreateElement("img", {}, { src: upobj.getPath() + "picdel.png", alt: "", width: "30", height: "30" });
                closeImg["onclick"] = function() { upobj.removeItem(upobj, closeImg); };
                innerDiv1.appendChild(closeImg);
                outerDiv.appendChild(innerDiv1);

                //
                var innerDiv2 = upobj.myCreateElement("div", { "width": this.size+"px", "height": this.size+"px", "border": "1px solid #eeeeee", "float": "left", "margin-top": "20px" });
                var viewImg = upobj.myCreateElement("img", { cursor: "pointer" }, { src: upobj.getPath() + "picbg.png", alt: "", width: this.size, height: this.size });
                viewImg["onclick"] = upobj.clickInputTag;
                innerDiv2.appendChild(viewImg);

                //
                var innerDiv3 = upobj.myCreateElement("div", { "width": this.size+"px", " height": this.size+"px", "position": " absolute", " left": " 0px", " top": " 20px", " opacity": "0.2" });
                var input = upobj.myCreateElement("input", { "display": "none" }, { "accept": "image/*", type: "file", "name": upobj.rootid + "_uploadpreview_" + upobj.num, "id": upobj.rootid + "_uploadpreview_" + upobj.num });
                input["onchange"] = function() { upobj.onInputChange(upobj, input); };

                outerDiv.appendChild(innerDiv1);
                outerDiv.appendChild(innerDiv2);
                outerDiv.appendChild(innerDiv3);
                outerDiv.appendChild(input);

                rootDiv.appendChild(outerDiv);

                upobj.rootNode.appendChild(rootDiv);
                upobj.num++;
            }

            MyUpload.prototype.removeItem = function(upobj, obj) {
                var obj = obj.parentNode.parentNode.parentNode;
                obj.parentNode.removeChild(obj);

                upobj.currentCount--;
                if (upobj.currentCount + 1 === upobj.maxnum)
                    upobj.createChild(upobj);
				if(typeof this.countChangeCallback=='function')
					this.countChangeCallback({max:this.maxnum,currentCount:upobj.currentCount})

            }

            MyUpload.prototype.clickInputTag = function() {
                var objs = this.parentNode.parentNode.childNodes;
                var obj;
                for (var key in objs) {
                    if (objs[key].nodeName == "INPUT") {
                        return objs[key].click();
                    }
                }
            }
            MyUpload.prototype.imgLoaded = function(upobj, close, preview) {
                var _this = this; //test
                upobj.currentCount++;
                close.style.display = "block";
                upobj.createChild(upobj);
                preview["onclick"] = null;
                preview.style["cursor"] = "";
				
				if(typeof this.countChangeCallback=='function')
					this.countChangeCallback({max:this.maxnum,currentCount:upobj.currentCount})
            }
            MyUpload.prototype.html5Reader = function(file, preview) {
                var _this = this; //test
                var file = file.files[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    preview.src = this.result;
                }
            }

            MyUpload.prototype.onInputChange = function(upobj, obj) {
                var brotherNodes = obj.parentNode.childNodes; //获取输入框所在的兄弟框
                var close = brotherNodes[0];
                var preview = brotherNodes[1].firstChild;
                var ext = obj.value.substring(obj.value.lastIndexOf(".") + 1).toLowerCase();

                // gif在IE浏览器暂时无法显示
                if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') {
                    alert("图片的格式必须为png或者jpg或者jpeg格式！");
                    return;
                }
                upobj.imgLoaded(upobj, close, preview);

                var isIE = navigator.userAgent.match(/MSIE/) != null,
                    isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null;

                if (isIE) {
                    obj.select();
                    var reallocalpath = document.selection.createRange().text;

                    // IE6浏览器设置img的src为本地路径可以直接显示图片
                    if (isIE6) {
                        pic.src = reallocalpath;
                    } else {
                        // 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片，但是可以通过滤镜来实现
                        pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
                        // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
                        pic.src = '';
                    }



                } else {
                    upobj.html5Reader(obj, preview);
                }
            }

            MyUpload.prototype.getPath = function() {
                var js = document.scripts || document.getElementsByTagName("script");
                var jsPath;
                for (var i = js.length; i > 0; i--) {
                    if (js[i - 1].src.indexOf("imguploadpreview.js") > -1) {
                        jsPath = js[i - 1].src.substring(0, js[i - 1].src.lastIndexOf("/") + 1);
                    }
                }
                return jsPath;
            }

            MyUpload._inited_ = true;
        }

    }

    var Init = function(id, maxnum,callback) {
        var obj = new MyUpload(id, maxnum,callback);
        obj.init();
        return this;
    }

    window.uploadpreview = Init;

})(window);